package com.yst.webplugin.fieldhandler;

import com.yst.spring.context.SpringContext;
import com.yst.webplugin.additional.ResultProcessor;
import com.yst.webplugin.additional.mask.MaskConfigUtil;
import com.yst.webplugin.additional.transform.TransformConfigUtil;
import com.yst.webplugin.annotation.HttpInfo;
import com.yst.webplugin.annotation.Query;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;

import java.lang.reflect.Field;
import java.util.*;

public class BatchQueryHandler implements IFieldHandler{
    @Override
    public boolean accept(Field field) {
        return Objects.nonNull(field.getAnnotation(Query.BatchQuery.class));
    }


    @Override
    public void handle(Field field, HttpInfo httpInfo) {

        Query.BatchQuery batchQuery=field.getAnnotation(Query.BatchQuery.class);

        List<Query> queryList= Arrays.asList(batchQuery.Queries());
        Map<String,Object> result=new HashMap<>();
        SqlToyLazyDao sqlToyLazyDao= SpringContext.getContext().getBean(SqlToyLazyDao.class);
        Map<String,Object> params=httpInfo.getBodyAs(HashMap.class);

        ResultProcessor resultProcessor= new ResultProcessor().addAllTransformConfig(TransformConfigUtil.fromField(field))
                .addAllFieldMaskConfig(MaskConfigUtil.fromField(field));

        for(Query query:queryList){
            String sqlOrName= query.sqlOrSqlName();
            sqlOrName= sqlOrName.isEmpty() ? query.name() : sqlOrName;
            sqlOrName= sqlOrName.isEmpty() ?field.getName():sqlOrName;
            List queryResult=sqlToyLazyDao.findBySql(sqlOrName,params,query.modelClass());
            resultProcessor.resetDisableField();
            resultProcessor.disableField(query.disabledFields());
            resultProcessor.addAllTransformConfig(TransformConfigUtil.fromClass(query.modelClass()));
            resultProcessor.deepProcess(queryResult,query.modelClass());
            result.put(query.name(),queryResult);
        }
        httpInfo.writeResult(result);

    }
}
